package com.lintf.bot.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lintf.bot.domain.BotGroup;
import com.lintf.bot.domain.BotGroupInvite;
import com.lintf.bot.domain.dto.BotGroupAddDTO;
import com.lintf.bot.domain.dto.BotGroupListDTO;
import com.lintf.bot.domain.dto.BotGroupRemoveDTO;
import com.lintf.bot.domain.dto.BotGroupUpdateDTO;
import com.lintf.bot.domain.enums.ReviewStatusEnums;
import com.lintf.bot.domain.enums.StatusEnums;
import com.lintf.bot.domain.enums.SysFileTypeEnums;
import com.lintf.bot.domain.vo.BotGroupListVo;
import com.lintf.bot.mapper.BotGroupMapper;
import com.lintf.bot.service.IBotGroupInviteService;
import com.lintf.bot.service.IBotGroupService;
import com.lintf.common.utils.SecurityUtils;
import com.lintf.common.utils.uuid.IdUtils;
import com.lintf.system.domain.SysFileInfo;
import com.lintf.system.service.ISysFileInfoService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author lintf
 * @description 针对表【bot_group】的数据库操作Service实现
 * @createDate 2024-03-13 12:47:48
 */
@Service
public class BotGroupServiceImpl extends ServiceImpl<BotGroupMapper, BotGroup>
        implements IBotGroupService {

    @Autowired
    private IBotGroupInviteService botGroupInviteService;
    @Autowired
    private ISysFileInfoService sysFileInfoService;

    @Override
    public List<BotGroupListVo> list(BotGroupListDTO dto) {
        LambdaQueryWrapper<BotGroupInvite> wrapper = new LambdaQueryWrapper<>();
        Long userId = SecurityUtils.getUserId();
        wrapper.select(BotGroupInvite::getGroupId)
                .eq(BotGroupInvite::getInviteUserId, userId)
                .eq(BotGroupInvite::getStatus, StatusEnums.COMPLETED.getValue())
                .eq(BotGroupInvite::getReview, ReviewStatusEnums.OK.getValue());
        List<Integer> inviteGroupIds = botGroupInviteService.list(wrapper).stream().map(BotGroupInvite::getGroupId).collect(Collectors.toList());
        LambdaQueryWrapper<BotGroup> groupWrapper = new LambdaQueryWrapper<>();
        if (!inviteGroupIds.isEmpty()) {
            groupWrapper.in(BotGroup::getId, inviteGroupIds).or();
        }
        groupWrapper.eq(BotGroup::getCreateBy, userId);
        List<BotGroupListVo> list = new ArrayList<>();
        BotGroupListVo vo;
        LambdaQueryWrapper<SysFileInfo> sysFileWrapper;
        List<BotGroup> records;
        if (dto.getIsPage()) {
            Page<BotGroup> page = new Page<>(dto.getPageNum(), dto.getPageSize());
            records = baseMapper.selectPage(page, groupWrapper).getRecords();
        } else {
            records = baseMapper.selectList(groupWrapper);
        }
        for (BotGroup group : records) {
            vo = new BotGroupListVo();
            BeanUtils.copyProperties(group, vo);
            if (dto.getIsPage()) {
                sysFileWrapper = new LambdaQueryWrapper<>();
                sysFileWrapper.eq(SysFileInfo::getRefId, group.getId())
                        .eq(SysFileInfo::getRefType, SysFileTypeEnums.GROUP.getValue());
                vo.setSysFileInfo(sysFileInfoService.getOne(sysFileWrapper));
            }
            list.add(vo);
        }
        return list;
    }

    @Override
    public List<BotGroup> searchOfList(BotGroupListDTO dto) {
        LambdaQueryWrapper<BotGroup> groupWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotEmpty(dto.getGroupName())) {
            groupWrapper.like(BotGroup::getGroupName, dto.getGroupName());
        }
        List<BotGroup> botGroups = baseMapper.selectList(groupWrapper);
        if (dto.getIsCount() && !botGroups.isEmpty()) {
            LambdaQueryWrapper<BotGroupInvite> wrapper;
            for (BotGroup group : botGroups) {
                wrapper = new LambdaQueryWrapper<>();
                wrapper.eq(BotGroupInvite::getGroupId, group.getId())
                        .eq(BotGroupInvite::getStatus, StatusEnums.COMPLETED.getValue())
                        .eq(BotGroupInvite::getReview, ReviewStatusEnums.OK.getValue());
                group.setGroupCount(Math.toIntExact(botGroupInviteService.count(wrapper) + 1));
            }
        }
        List<BotGroupListVo> list = new ArrayList<>();
        BotGroupListVo vo;
        LambdaQueryWrapper<SysFileInfo> sysFileWrapper;
        for (BotGroup group : botGroups) {
            vo = new BotGroupListVo();
            BeanUtils.copyProperties(group, vo);
            sysFileWrapper = new LambdaQueryWrapper<>();
            sysFileWrapper.eq(SysFileInfo::getRefId, group.getId())
                    .eq(SysFileInfo::getRefType, SysFileTypeEnums.GROUP.getValue());
            vo.setSysFileInfo(sysFileInfoService.getOne(sysFileWrapper));
            list.add(vo);
        }
        return list.stream().sorted(Comparator.comparing(BotGroupListVo::getGroupCount).reversed()).collect(Collectors.toList());
    }


    @Override
    @Transactional
    public void add(BotGroupAddDTO dto) {
        BotGroup botGroup = new BotGroup();
        BeanUtils.copyProperties(dto, botGroup);
//        botGroup.setCreateParams();
        baseMapper.insert(botGroup);
        if (dto.getSysFileInfo() != null) {
            dto.getSysFileInfo().setId(IdUtils.simpleUUID());
            dto.getSysFileInfo().setRefType(SysFileTypeEnums.GROUP.getValue());
            dto.getSysFileInfo().setRefId(botGroup.getId());
//            dto.getSysFileInfo().setCreateParams();
            sysFileInfoService.save(dto.getSysFileInfo());
        }
        if (dto.getInviteUserIds() != null && !dto.getInviteUserIds().isEmpty()) {
            List<BotGroupInvite> invites = new ArrayList<>();
            dto.getInviteUserIds().forEach(userId -> {
                BotGroupInvite botGroupInvite = new BotGroupInvite();
                botGroupInvite.setGroupId(botGroup.getId())
                        .setInviteUserId(userId);
//                        .setCreateParams();
                invites.add(botGroupInvite);
            });
            botGroupInviteService.saveBatch(invites);
        }
    }

    @Override
    @Transactional
    public void update(BotGroupUpdateDTO dto) {
        BotGroup botGroup = new BotGroup();
        BeanUtils.copyProperties(dto, botGroup);
//        botGroup.setUpdateParams();
        baseMapper.updateById(botGroup);
        if (dto.getSysFileInfo() != null) {
            LambdaQueryWrapper<SysFileInfo> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(SysFileInfo::getRefId, dto.getId())
                    .eq(SysFileInfo::getRefType, SysFileTypeEnums.GROUP.getValue());
            sysFileInfoService.remove(wrapper);
            dto.getSysFileInfo().setId(IdUtils.simpleUUID());
            dto.getSysFileInfo().setRefType(SysFileTypeEnums.GROUP.getValue());
            dto.getSysFileInfo().setRefId(dto.getId());
//            dto.getSysFileInfo().setCreateParams();
            sysFileInfoService.save(dto.getSysFileInfo());
        }
    }

    @Override
    public void remove(BotGroupRemoveDTO dto) {
        BotGroup botGroup = new BotGroup();
        BeanUtils.copyProperties(dto, botGroup);
//        botGroup.setUpdateParams();
        baseMapper.deleteById(dto);
    }
}




